var Express = require("express");
var ExpressSession = require("express-session");
var Path = require("path");
var BodyParser = require("body-parser");
var CookieParser = require("cookie-parser");
var RedisStore = require("connect-redis")(ExpressSession);
var Logger = require("morgan");
var Favicon = require('serve-favicon');

var Config = require("./config");

var app = Express();

// view engine setup
app.set("views", Path.join(__dirname, "views/main"));
app.set("view engine", "ejs");

// uncomment after placing your favicon in /public
app.use(Favicon(__dirname + "/public/favicon.ico"));
app.use(Logger("dev"));
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use(Express.static(Path.join(__dirname, "public")));

// cookies & session
app.use(ExpressSession({
    store: new RedisStore(Config.Redis.Session),
    secret: Config.Common.Session_Ssecret,
    resave: true,
    saveUninitialized: false,
    cookie: {domain: Config.Common.Domain}
}));
app.use(CookieParser());

// routes
app.use("/", require("./routes/main"));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error("Not Found");
    err.status = 404;
    next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render("error", {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render("error", {
        message: err.message,
        error: {}
    });
});

module.exports = app;
